import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
  Spin,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useHistory, useParams } from 'react-router-dom'
import styles from './index.module.scss'
// 富文本编辑器组件
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'

import Channel from '@/components/channel'
import { useState, useRef } from 'react'
import { useDispatch } from 'react-redux'
import { updateArticle } from '@/store/actions'
import { useEffect } from 'react'
import { http } from '@/utils'

const Publish = () => {
  // 封面图上传
  // 1. 上传图片的列表数据格式：fileList = [{url:'1'},{url:'2'}...]
  const [fileList, setFileList] = useState([])

  const onUploadChange = (info) => {
    // info.fileList 用来获取当前的文件列表
    const fileList = info.fileList.map((file) => {
      console.log(1, file)
      // 刚从本地上传的图片
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      // 已有图片操作（删除已上传的图片列表）
      return file
    })
    // 存储最新上传图片列表
    fileListRef.current = fileList
    setFileList(fileList)
  }

  // 2. 控制封面数量
  const [maxCount, setMaxCount] = useState(1)
  const fileListRef = useRef([])
  const changeType = (e) => {
    const count = e.target.value
    setMaxCount(count)
    // 动态控制封面显示图片数量
    if (count === 1) {
      // 单图，只展示第一张
      const firstImg = fileListRef.current[0]
      setFileList(!firstImg ? [] : [firstImg])
    } else if (count === 3) {
      // 三图，展示所有图片
      setFileList(fileListRef.current)
    }
  }

  // 3. 提交数据
  const dispatch = useDispatch()
  const history = useHistory()
  // 复用发布文章
  const saveArticles = async (values, saveType) => {
    if (values.type !== fileList.length)
      return message.warning('封面数量与所选类型不匹配')

    const { type, ...rest } = values
    // 后台发布文章需要的数据格式
    const data = {
      ...rest,
      cover: {
        type,
        // images: fileList
        images: fileList.map((item) => item.url),
      },
    }

    // 如果是编辑，就将 id 存储到 data 中，传递给接口
    if (isEdit) {
      data.id = articleId
    }

    console.log('data:', data)

    try {
      // true 草稿
      // false 正常发布
      await dispatch(updateArticle(data, saveType === 'add', isEdit))
      const text = isEdit ? '修改' : '发布'
      const showMsg = saveType === 'add' ? `${text}成功` : '存入草稿成功'
      message.success(showMsg, 1, () => {
        history.push('/home/article')
      })
    } catch {}
  }
  const onFinish = async (values) => {
    saveArticles(values, 'add')
  }

  // 4. 存入草稿
  // 创建表单实例
  // 注意：此处的 form 是从数组中解构出来的
  const [form] = Form.useForm()

  const saveDraft = async () => {
    try {
      const values = await form.validateFields()

      console.log(values)
      saveArticles(values, 'draft')
    } catch {}
  }

  // 5. 编辑和发布状态处理
  const { articleId } = useParams()
  // 编辑状态true
  const isEdit = !!articleId
  // console.log(isEdit)
  // 6. 编辑状态=》回填数据
  // 添加loading
  const [loading, setLoading] = useState(true)
  useEffect(() => {
    const loadData = async () => {
      if (!isEdit) {
        // 动态设置表单数据
        form.resetFields()
        // 格式化封面图片数据
        const imageList = []
        setFileList(imageList)
        setMaxCount(1)
        fileListRef.current = imageList
        setLoading(false)

        return
      }
      // 编辑
      try {
        // 获取文章信息
        const res = await http.get(`/mp/articles/${articleId}`)
        const {
          id,
          title,
          channel_id,
          content,
          cover: { type, images },
        } = res.data
        // 组装表单文章数据
        const formValue = {
          id,
          title,
          channel_id,
          content,
          type,
          // images,
        }
        // const { images: imgs, ...formValue } = article
        // 动态设置表单数据
        form.setFieldsValue(formValue)

        // 格式化封面图片数据
        const imageList = images.map((item) => ({ url: item }))
        setFileList(imageList)
        setMaxCount(formValue.type)
        fileListRef.current = imageList
        setLoading(false)
      } catch {}
    }
    // 执行
    loadData()
  }, [articleId, isEdit, form])

  // 修复回填数据问题
  const fixContent = (val) => {
    // console.log(val)
    if (val === '<p><br></p>') {
      form.setFieldsValue({ content: '' })
    }
  }
  return (
    <div className={styles.root}>
      <Spin spinning={loading}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {' '}
                {isEdit ? '修改文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }>
          <Form
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ type: 1, content: '' }}
            onFinish={onFinish}>
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}>
              <Input placeholder="请输入文章标题" />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择文章频道' }]}>
              <Channel />
            </Form.Item>

            <Form.Item label="封面">
              <Form.Item name="type">
                <Radio.Group onChange={changeType}>
                  <Radio value={1}>单图</Radio>
                  <Radio value={3}>三图</Radio>
                  <Radio value={0}>无图</Radio>
                  {/* <Radio value={-1}>自动</Radio> */}
                </Radio.Group>
              </Form.Item>
              {maxCount > 0 && (
                <Upload
                  name="image"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList
                  action="http://geek.itheima.net/v1_0/upload"
                  maxCount={maxCount}
                  multiple={maxCount > 1}
                  fileList={fileList}
                  onChange={onUploadChange}>
                  <div style={{ marginTop: 8 }}>
                    <PlusOutlined />
                  </div>
                </Upload>
              )}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}>
              <ReactQuill
                onChange={fixContent}
                className="publish-quill"
                theme="snow"
                placeholder="请输入文章内容"
              />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  {isEdit ? '修改文章' : '发布文章'}
                </Button>
                <Button size="large" onClick={saveDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </Spin>
    </div>
  )
}

export default Publish
